package com.todo.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.todo.demo.Model.*;
import com.todo.demo.Service.LoginService;
import com.todo.demo.Service.PlanAndTaskService;
import com.todo.demo.Util.HttpRequest;
import com.todo.demo.Util.MD5;
import com.todo.demo.Util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@EnableAutoConfiguration
@RequestMapping("/loginMain")
@Component
public class LoginController {
    @Autowired
    private LoginService userService;
    @Autowired
    private PlanAndTaskService planAndTaskService;

    @RequestMapping("addUser")
    @ResponseBody
    public Object addUser(User user) {

        int count = userService.checkUserExist(user);
        /**
         * 判断账号重复
         */
        if (count > 0) {
            User userByLocal = userService.getUserByName(user.getUser_name());

            Result result = new Result();
            result.setCode(-1);
            result.setMsg("账号已存在");
            result.setData(userByLocal.getId());

            return JSON.toJSON(result);
        }

        if (user.getUser_name().trim().equals("") || user.getUser_name().trim().isEmpty()) {
            return JSON.toJSON(Util.getInstance().ResultFail("账号不能为空"));
        }
        if (user.getPassword().trim().equals("") || user.getPassword().trim().isEmpty()) {
            return JSON.toJSON(Util.getInstance().ResultFail("密码不能为空"));
        }
        /**
         * 获取系统时间
         */
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        user.setCreate_time(df.format(new Date()));

        /**
         *  校验通过
         *  插入这条记录
         */
        int resultData = userService.addUser(user);
        if (resultData <= 0) {
            return JSON.toJSON(Util.getInstance().ResultFail("未知错误"));
        }
        user.setId(user.getId());

        return JSON.toJSON(Util.getInstance().ResultSuccessful(user.getId()));
    }

    //    @RequestMapping("login")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(User user) {

        if (user == null) {
            return JSON.toJSON(Util.getInstance().ResultFail("参数错误"));
        }

        int count = userService.checkUserExist(user);
        /**
         * 判断账号是否存在
         */
        if (count <= 0) {
            return JSON.toJSON(Util.getInstance().ResultFail("账号不存在，请先注册"));
        }

        if (user.getUser_name().trim().equals("") || user.getUser_name().trim().isEmpty()) {
            return JSON.toJSON(Util.getInstance().ResultFail("账号不能为空"));
        }
        if (user.getPassword().trim().equals("") || user.getPassword().trim().isEmpty()) {
            return JSON.toJSON(Util.getInstance().ResultFail("密码不能为空"));
        }

        User userByLocal = userService.getUserByName(user.getUser_name());
        if (!user.getPassword().equals(userByLocal.getPassword())) {
            return JSON.toJSON(Util.getInstance().ResultFail("密码错误"));
        }
        return JSON.toJSON(Util.getInstance().ResultSuccessful(userByLocal));
    }

    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public Object getUserInfo(String js_code) {
        String appID = "wx5d6db64a11aeb2de";
        String appSecret = "ee51ab838de63f97460b5467d3342656";

        String requestByWx = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", "appid=" + appID + "&secret=" + appSecret + "&grant_type=authorization_code&js_code=" + js_code);
        JSONObject jsonObject = (JSONObject) JSON.parse(requestByWx);

        String openId = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        User user = new User();
        user.setUser_name(openId);
        user.setPassword(MD5.GetMD5Code("1"));
        /**doSync
         *  这个方法会判断用户是否存在
         *  不存在就插入一条新用户
         *  存在就什么都不做
         */
        JSONObject user1 = (JSONObject) addUser(user);
        return user1.get("data");
    }


    @RequestMapping(value = "/updateUserAvatar", method = RequestMethod.POST)
    public Object updateUserAvatar(String userId, String avatarUrl, String nickName) {

        User user = new User();
        user.setId(Long.valueOf(userId));
        user.setAvatar_url(avatarUrl);
        user.setNick_name(nickName);

        /**
         * 获取系统时间
         */
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        user.setLast_login_time(df.format(new Date()));

        userService.updateUserAvatar(user);
        return null;
    }

    /**
     * 收集用户的formId
     *
     * @return
     */
    @RequestMapping(value = "/setFormId", method = RequestMethod.POST)
    public Object setFormId(String formId, String user_id) {

        User user = new User();
        user.setForm_id(formId);
        user.setId(Long.valueOf(user_id));

        userService.updateFormId(user);
        return null;
    }

    @RequestMapping(value = "/getAccessToken", method = RequestMethod.POST)
    public Object getAccessToken(String userId) {

        KeyAndValueTodo keyAndValue1 = userService.getAccessToken();
        if (keyAndValue1 == null) {
            Util.getInstance().getToken(userService);
        }

        String res = sendMsg(userId, (String) userService.getAccessToken().getTodo_value());

        JSONObject jsonObject1 = (JSONObject) JSON.parse(res);
        if (jsonObject1.getInteger("errcode") == 42001) {

            res = sendMsg(userId, Util.getInstance().getToken(userService));
        }
        return null;
    }

    private String sendMsg(String userId, String access_token) {
        User user = new User();
        user.setId(Long.valueOf(userId));

        User user1 = userService.getUserById(user);
        List<HashMap<String, Object>> plans = planAndTaskService.findAllPlanWithTask(1, 100, Long.valueOf(userId));
        if (plans.size() <= 0) {
            return "没有计划";
        }
        Plan plan = (Plan) plans.get(0).get("plan");
        String plan_title = plan.getPlan_title();
        String plan_create_time = plan.getPlan_create_time();

        /**
         *  发送消息
         */

        String params;

        /**
         *  data
         */
        KeyWord keyWord = new KeyWord();
        KeyWord.KeywordValue keyWordValue = new KeyWord().new KeywordValue();
        keyWordValue.setValue("鲁迅说：没有完成计划的人，不要吃饭");
        keyWord.setKeyword1(keyWordValue);
        keyWordValue = new KeyWord().new KeywordValue();
        keyWordValue.setValue(plan_title);
        keyWord.setKeyword2(keyWordValue);
        keyWordValue = new KeyWord().new KeywordValue();
        keyWordValue.setValue(plan_create_time);
        keyWord.setKeyword3(keyWordValue);

        /**
         *  总体
         */
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("touser", user1.getUser_name());
        paramsMap.put("template_id", "8A2Gh9i9V5QafAWkb7uGn2agCkuqpb5O86tOwGJfHxQ");
        paramsMap.put("form_id", user1.getForm_id());
        paramsMap.put("page", "pages/index/index");
        paramsMap.put("data", keyWord);

        params = JSON.toJSONString(paramsMap);
        /**
         * 发送模板消息的参数
         */

        String res = Util.getInstance().post("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?&access_token=" + access_token, params);

        JSONObject map = (JSONObject) JSONObject.parse(res);

        MsgLog msgLog = new MsgLog();
        msgLog.setCode(map.get("errcode").toString());
        msgLog.setError_msg(map.get("errmsg").toString());
        msgLog.setUser_id(Long.valueOf(userId));

        userService.addMsgLog(msgLog);
        return res;
    }

    /**
     * 获取分享信息
     *
     * @return
     */
    @RequestMapping(value = "/getShareInfo", method = RequestMethod.POST)
    public Object getShareInfo() {

        ShareInfo shareInfo = userService.getShareInfo();
        return shareInfo;
    }

    /**
     * 定时任务
     */
    private int count = 0;

    //    @Scheduled(cron = "*/6 * * * * ?")
    @Scheduled(cron = "0 0 12 * * ?")
    private void process() {
//        System.out.println("[" + Thread.currentThread().getName() + "]" + "this is scheduler task runing  " + (count++));
//
//        List<User> userList = userService.findAllUser(1,10000);
//        for (int i = 0; i < userList.size(); i++) {
//            try {
//                int day = calculateTimeDifferenceByCalendar(String.valueOf(userList.get(i).getLast_login_time()));
//                if (day > 4) {
//                    System.out.println("准备给【" + userList.get(i).getNick_name() + "】发消息...");
//
//                    String res;
//                    if (userService.getAccessToken() == null) {
//                        res = sendMsg(String.valueOf(userList.get(i).getId()), getToken());
//                    } else {
//                        res = sendMsg(String.valueOf(userList.get(i).getId()), (String) userService.getAccessToken().getTodo_value());
//                    }
//
//                    JSONObject jsonObject1 = (JSONObject) JSON.parse(res);
//                    if (jsonObject1.getInteger("errcode") == 42001 || jsonObject1.getInteger("errcode") == 40001) {
//                        res = sendMsg(String.valueOf(userList.get(i).getId()), getToken());
//                    }
//
//                    System.out.println("发送消息执行完成，结果：" + res);
//
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        }
    }

}